<template>
  <div class="ip-query-tool-box">
    <div class="ip-query-tool">
      <!-- 头部区域 -->
      <div class="header">
        <div class="title-section">
          <div class="logo">
            <svg
              width="32"
              height="32"
              viewBox="0 0 24 24"
              fill="none"
              xmlns="http://www.w3.org/2000/svg"
            >
              <path
                d="M12 21C16.9706 21 21 16.9706 21 12C21 7.02944 16.9706 3 12 3C7.02944 3 3 7.02944 3 12C3 16.9706 7.02944 21 12 21Z"
                stroke="currentColor"
                stroke-width="2"
              />
              <path
                d="M12 15C13.6569 15 15 13.6569 15 12C15 10.3431 13.6569 9 12 9C10.3431 9 9 10.3431 9 12C9 13.6569 10.3431 15 12 15Z"
                stroke="currentColor"
                stroke-width="2"
              />
              <path d="M12 3V5" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
              <path d="M12 19V21" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
              <path d="M3 12H5" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
              <path d="M19 12H21" stroke="currentColor" stroke-width="2" stroke-linecap="round" />
            </svg>
          </div>
          <div>
            <h1>IP 查询工具</h1>
            <p>实时查询 IP 地址的详细信息</p>
          </div>
        </div>
        <div class="controls">
          <button @click="queryIP" class="query-btn" :disabled="loading">
            <span class="btn-icon" v-if="!loading">🌐</span>
            <span class="btn-icon loading" v-else>⏳</span>
            {{ loading ? '查询中...' : '查询IP' }}
          </button>
          <button @click="queryMyIP" class="myip-btn">
            <span class="btn-icon">👤</span>
            我的IP
          </button>
          <button @click="clearAll" class="clear-btn">
            <span class="btn-icon">🗑️</span>
            清空
          </button>
          <button @click="returnFn" class="query-btn">返回</button>
        </div>
      </div>

      <!-- 查询输入区域 -->
      <div class="query-section">
        <div class="input-group">
          <label for="ip-input">IP 地址</label>
          <div class="input-container">
            <input
              id="ip-input"
              v-model="ipAddress"
              type="text"
              placeholder="请输入要查询的 IP 地址（留空查询本机IP）"
              @keyup.enter="queryIP"
              class="ip-input"
            />
            <div class="input-actions">
              <button @click="pasteFromClipboard" class="icon-btn" title="粘贴">📎</button>
            </div>
          </div>
        </div>
      </div>

      <!-- IP 信息展示 -->
      <div class="info-section" v-if="ipInfo">
        <div class="section-header">
          <h3>IP 详细信息</h3>
          <div class="info-badge" :class="getRiskLevel(ipInfo)">
            {{ getRiskLevelText(ipInfo) }}
          </div>
        </div>

        <div class="info-grid">
          <!-- 基础信息 -->
          <div class="info-card">
            <div class="card-header">
              <span class="card-icon">📊</span>
              <h4>基础信息</h4>
            </div>
            <div class="info-content">
              <div class="info-item">
                <label>IP 地址</label>
                <span class="info-value ip-address">{{ ipInfo.ip }}</span>
              </div>
              <div class="info-item">
                <label>地理位置</label>
                <span class="info-value">
                  {{ [ipInfo.country, ipInfo.region, ipInfo.city].filter(Boolean).join(' · ') }}
                </span>
              </div>
              <div class="info-item">
                <label>运营商</label>
                <span class="info-value">{{ ipInfo.isp || '未知' }}</span>
              </div>
            </div>
          </div>

          <!-- 网络信息 -->
          <div class="info-card">
            <div class="card-header">
              <span class="card-icon">🌍</span>
              <h4>网络信息</h4>
            </div>
            <div class="info-content">
              <div class="info-item">
                <label>国家代码</label>
                <span class="info-value">{{ ipInfo.countryCode || '未知' }}</span>
              </div>
              <div class="info-item">
                <label>时区</label>
                <span class="info-value">{{ ipInfo.timezone || '未知' }}</span>
              </div>
              <div class="info-item">
                <label>邮政编码</label>
                <span class="info-value">{{ ipInfo.zip || '未知' }}</span>
              </div>
            </div>
          </div>

          <!-- 地理位置 -->
          <div class="info-card">
            <div class="card-header">
              <span class="card-icon">📍</span>
              <h4>地理位置</h4>
            </div>
            <div class="info-content">
              <div class="info-item">
                <label>经纬度</label>
                <span class="info-value">
                  {{ ipInfo.lat ? `${ipInfo.lat}, ${ipInfo.lon}` : '未知' }}
                </span>
              </div>
              <div class="info-item">
                <label>城市</label>
                <span class="info-value">{{ ipInfo.city || '未知' }}</span>
              </div>
              <div class="info-item">
                <label>区域</label>
                <span class="info-value">{{ ipInfo.regionName || '未知' }}</span>
              </div>
            </div>
          </div>

          <!-- 技术信息 -->
          <div class="info-card">
            <div class="card-header">
              <span class="card-icon">⚙️</span>
              <h4>技术信息</h4>
            </div>
            <div class="info-content">
              <div class="info-item">
                <label>IP 版本</label>
                <span class="info-value">{{ ipInfo.ip.includes(':') ? 'IPv6' : 'IPv4' }}</span>
              </div>
              <div class="info-item">
                <label>组织</label>
                <span class="info-value">{{ ipInfo.org || ipInfo.isp || '未知' }}</span>
              </div>
              <div class="info-item">
                <label>ASN</label>
                <span class="info-value">{{ ipInfo.as || '未知' }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 地图预览 -->
        <div class="map-section" v-if="ipInfo.lat && ipInfo.lon">
          <div class="card-header">
            <span class="card-icon">🗺️</span>
            <h4>地理位置预览</h4>
          </div>
          <div class="map-placeholder">
            <div class="map-coordinates">
              <span>纬度: {{ ipInfo.lat }}</span>
              <span>经度: {{ ipInfo.lon }}</span>
            </div>
            <button @click="openInMaps" class="map-btn">
              <span class="btn-icon">🗺️</span>
              在地图中查看
            </button>
          </div>
        </div>
      </div>

      <!-- 查询历史 -->
      <div class="history-section" v-if="queryHistory.length > 0">
        <div class="section-header">
          <h3>查询历史</h3>
          <button @click="clearHistory" class="text-btn">清空历史</button>
        </div>
        <div class="history-list">
          <div
            v-for="(history, index) in queryHistory.slice(0, 5)"
            :key="index"
            class="history-item"
            @click="selectHistory(history)"
          >
            <span class="history-ip">{{ history.ip }}</span>
            <span class="history-location">{{ history.city || '未知位置' }}</span>
            <span class="history-time">{{ formatTime(history.timestamp) }}</span>
          </div>
        </div>
      </div>

      <!-- 状态提示 -->
      <transition name="slide-down">
        <div v-if="showStatus" :class="['status', statusType]">
          <div class="status-content">
            <span class="status-icon">{{ statusType === 'success' ? '✅' : '❌' }}</span>
            {{ statusMessage }}
          </div>
        </div>
      </transition>

      <!-- 统计信息 -->
      <div class="stats-section">
        <div class="stats-grid">
          <div class="stat-card">
            <div class="stat-icon">🔍</div>
            <div class="stat-info">
              <span class="stat-value">{{ totalQueries }}</span>
              <span class="stat-label">总查询次数</span>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">🌏</div>
            <div class="stat-info">
              <span class="stat-value">{{ uniqueCountries }}</span>
              <span class="stat-label">国家/地区</span>
            </div>
          </div>
          <div class="stat-card">
            <div class="stat-icon">⚡</div>
            <div class="stat-info">
              <span class="stat-value">{{ responseTime }}ms</span>
              <span class="stat-label">平均响应</span>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
// 响应式数据
const ipAddress = ref('')
const ipInfo = ref(null)
const loading = ref(false)
const showStatus = ref(false)
const statusMessage = ref('')
const statusType = ref('success')
const queryHistory = ref([])
const responseTime = ref(0)
const Router = useRouter()
const returnFn = () => {
  Router.go(-1)
}
// 统计信息
const totalQueries = computed(() => queryHistory.value.length)
const uniqueCountries = computed(() => {
  const countries = new Set(queryHistory.value.map(item => item.country).filter(Boolean))
  return countries.size
})

// IP 查询函数
const queryIP = async () => {
  if (!ipAddress.value.trim()) {
    await queryMyIP()
    return
  }

  // 验证 IP 地址格式
  if (!isValidIP(ipAddress.value)) {
    showStatusMessage('请输入有效的 IP 地址', 'error')
    return
  }

  await fetchIPInfo(ipAddress.value)
}

// 查询本机 IP
const queryMyIP = async () => {
  ipAddress.value = ''
  await fetchIPInfo('')
}

// 获取 IP 信息
const fetchIPInfo = async (ip = '') => {
  loading.value = true
  const startTime = Date.now()

  try {
    // 使用多个 API 端点提高成功率
    const apiEndpoints = [
      `http://ip-api.com/json/${ip}?fields=66846719&lang=zh-CN`,
      `https://api.ip.sb/geoip/${ip}`,
      `https://ipapi.co/${ip}/json/`
    ]

    let response = null
    for (const endpoint of apiEndpoints) {
      try {
        response = await fetch(endpoint)
        if (response.ok) break
      } catch (error) {
        console.log(`API ${endpoint} 失败:`, error)
        continue
      }
    }

    if (!response || !response.ok) {
      throw new Error('所有 API 服务均不可用')
    }

    const data = await response.json()

    // 标准化响应数据
    const standardizedData = standardizeIPData(data)

    ipInfo.value = standardizedData
    addToHistory(standardizedData)

    responseTime.value = Date.now() - startTime
    showStatusMessage('查询成功!', 'success')

  } catch (error) {
    console.error('IP 查询错误:', error)
    showStatusMessage(`查询失败: ${error.message}`, 'error')
    ipInfo.value = null
  } finally {
    loading.value = false
  }
}

// 标准化 IP 数据
const standardizeIPData = (data) => {
  // 处理不同 API 的响应格式
  return {
    ip: data.ip || data.query || '',
    country: data.country || data.country_name || '',
    countryCode: data.countryCode || data.country_code || '',
    region: data.region || data.regionName || data.state || '',
    regionName: data.regionName || data.region || '',
    city: data.city || '',
    zip: data.zip || data.postal || '',
    lat: data.lat || data.latitude || '',
    lon: data.lon || data.longitude || '',
    timezone: data.timezone || '',
    isp: data.isp || data.org || data.asn?.org || '',
    org: data.org || data.isp || '',
    as: data.as || data.asn?.asn || ''
  }
}

// 验证 IP 地址格式
const isValidIP = (ip) => {
  const ipv4Regex = /^(\d{1,3}\.){3}\d{1,3}$/
  const ipv6Regex = /^([0-9a-fA-F]{1,4}:){7}[0-9a-fA-F]{1,4}$/
  return ipv4Regex.test(ip) || ipv6Regex.test(ip)
}

// 添加到查询历史
const addToHistory = (data) => {
  const historyItem = {
    ...data,
    timestamp: Date.now()
  }

  queryHistory.value.unshift(historyItem)

  // 限制历史记录数量
  if (queryHistory.value.length > 10) {
    queryHistory.value = queryHistory.value.slice(0, 10)
  }

  // 保存到 localStorage
  localStorage.setItem('ipQueryHistory', JSON.stringify(queryHistory.value))
}

// 从剪贴板粘贴
const pasteFromClipboard = async () => {
  try {
    const text = await navigator.clipboard.readText()
    if (isValidIP(text)) {
      ipAddress.value = text
      showStatusMessage('已从剪贴板粘贴 IP 地址', 'success')
    } else {
      showStatusMessage('剪贴板内容不是有效的 IP 地址', 'error')
    }
  } catch (error) {
    showStatusMessage('无法访问剪贴板', 'error')
  }
}

// 选择历史记录
const selectHistory = (history) => {
  ipAddress.value = history.ip
  ipInfo.value = history
}

// 清空历史记录
const clearHistory = () => {
  queryHistory.value = []
  localStorage.removeItem('ipQueryHistory')
  showStatusMessage('已清空查询历史', 'success')
}

// 清空所有内容
const clearAll = () => {
  ipAddress.value = ''
  ipInfo.value = null
  showStatusMessage('已清空', 'success')
}

// 在地图中查看
const openInMaps = () => {
  if (ipInfo.value.lat && ipInfo.value.lon) {
    const url = `https://maps.google.com/?q=${ipInfo.value.lat},${ipInfo.value.lon}`
    window.open(url, '_blank')
  }
}

// 风险评估
const getRiskLevel = (info) => {
  // 简单的风险评估逻辑
  if (info.countryCode === 'CN') return 'safe'
  if (['US', 'RU', 'KP'].includes(info.countryCode)) return 'warning'
  return 'unknown'
}

const getRiskLevelText = (info) => {
  const level = getRiskLevel(info)
  const texts = {
    safe: '安全',
    warning: '注意',
    unknown: '未知'
  }
  return texts[level]
}

// 格式化时间
const formatTime = (timestamp) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN')
}

// 显示状态消息
const showStatusMessage = (message, type = 'success') => {
  statusMessage.value = message
  statusType.value = type
  showStatus.value = true

  setTimeout(() => {
    showStatus.value = false
  }, 3000)
}

// 组件挂载时加载历史记录
onMounted(() => {
  const savedHistory = localStorage.getItem('ipQueryHistory')
  if (savedHistory) {
    queryHistory.value = JSON.parse(savedHistory)
  }

  // 自动查询本机 IP
  queryMyIP()
})
</script>

<style scoped>
.ip-query-tool-box {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}
.ip-query-tool {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: 'Inter', -apple-system, BlinkMacSystemFont, sans-serif;

  min-height: 100vh;
}

/* 头部样式 */
.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 24px;
  border-radius: 20px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
  border: 1px solid rgba(255, 255, 255, 0.2);
}

.title-section {
  display: flex;
  align-items: center;
  gap: 16px;
}

.logo {
  width: 60px;
  height: 60px;
  background: linear-gradient(135deg, #667eea, #764ba2);
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
}

.title-section h1 {
  margin: 0;
  color: #2d3748;
  font-size: 28px;
  font-weight: 700;
}

.title-section p {
  margin: 4px 0 0 0;
  color: #718096;
  font-size: 14px;
}

.controls {
  display: flex;
  gap: 12px;
}

/* 按钮样式 */
button {
  padding: 12px 20px;
  border: none;
  border-radius: 12px;
  cursor: pointer;
  font-weight: 600;
  transition: all 0.3s ease;
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
}

button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

.query-btn {
  background: linear-gradient(135deg, #4299e1, #3182ce);
  color: white;
}

.query-btn:hover:not(:disabled) {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(66, 153, 225, 0.4);
}

.myip-btn {
  background: linear-gradient(135deg, #48bb78, #38a169);
  color: white;
}

.myip-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(72, 187, 120, 0.4);
}

.clear-btn {
  background: linear-gradient(135deg, #f56565, #e53e3e);
  color: white;
}

.clear-btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 6px 20px rgba(245, 101, 101, 0.4);
}

.text-btn {
  background: none;
  color: #4299e1;
  padding: 8px 16px;
}

.text-btn:hover {
  background: #f7fafc;
}

.btn-icon.loading {
  animation: spin 1s linear infinite;
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

/* 查询区域 */
.query-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 24px;
  border-radius: 20px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.input-group label {
  display: block;
  margin-bottom: 8px;
  font-weight: 600;
  color: #2d3748;
}

.input-container {
  position: relative;
  display: flex;
  align-items: center;
}

.ip-input {
  flex: 1;
  padding: 16px;
  border: 2px solid #e2e8f0;
  border-radius: 12px;
  font-size: 16px;
  font-family: 'JetBrains Mono', monospace;
  background: white;
  transition: border-color 0.3s ease;
}

.ip-input:focus {
  outline: none;
  border-color: #4299e1;
  box-shadow: 0 0 0 3px rgba(66, 153, 225, 0.1);
}

.input-actions {
  position: absolute;
  right: 12px;
}

.icon-btn {
  padding: 8px;
  background: none;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 16px;
  transition: background 0.3s ease;
}

.icon-btn:hover {
  background: #f7fafc;
}

/* 信息展示 */
.info-section,
.history-section,
.stats-section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10px);
  padding: 24px;
  border-radius: 20px;
  margin-bottom: 24px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: #2d3748;
  font-size: 20px;
  font-weight: 600;
}

.info-badge {
  padding: 4px 12px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 600;
}

.info-badge.safe {
  background: #c6f6d5;
  color: #22543d;
}

.info-badge.warning {
  background: #fed7d7;
  color: #742a2a;
}

.info-badge.unknown {
  background: #e2e8f0;
  color: #4a5568;
}

.info-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 20px;
  margin-bottom: 24px;
}

.info-card {
  background: #f7fafc;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e2e8f0;
}

.card-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.card-icon {
  font-size: 20px;
}

.card-header h4 {
  margin: 0;
  color: #2d3748;
  font-size: 16px;
  font-weight: 600;
}

.info-content {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.info-item label {
  font-weight: 500;
  color: #718096;
  font-size: 14px;
}

.info-value {
  font-weight: 600;
  color: #2d3748;
  text-align: right;
}

.ip-address {
  font-family: 'JetBrains Mono', monospace;
  color: #4299e1;
}

/* 地图区域 */
.map-section {
  background: #f7fafc;
  border-radius: 12px;
  padding: 20px;
  border: 1px solid #e2e8f0;
}

.map-placeholder {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  border: 2px dashed #cbd5e0;
}

.map-coordinates {
  display: flex;
  gap: 20px;
  font-family: 'JetBrains Mono', monospace;
  color: #4a5568;
}

.map-btn {
  background: linear-gradient(135deg, #48bb78, #38a169);
  color: white;
}

/* 历史记录 */
.history-list {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.history-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px 16px;
  background: #f7fafc;
  border-radius: 8px;
  cursor: pointer;
  transition: all 0.3s ease;
}

.history-item:hover {
  background: #edf2f7;
  transform: translateX(4px);
}

.history-ip {
  font-family: 'JetBrains Mono', monospace;
  font-weight: 600;
  color: #2d3748;
}

.history-location {
  color: #718096;
  font-size: 14px;
}

.history-time {
  color: #a0aec0;
  font-size: 12px;
}

/* 统计信息 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.stat-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 20px;
  background: #f7fafc;
  border-radius: 12px;
}

.stat-icon {
  font-size: 32px;
}

.stat-info {
  display: flex;
  flex-direction: column;
}

.stat-value {
  font-size: 24px;
  font-weight: 700;
  color: #2d3748;
}

.stat-label {
  font-size: 14px;
  color: #718096;
}

/* 状态提示 */
.slide-down-enter-active,
.slide-down-leave-active {
  transition: all 0.3s ease;
}

.slide-down-enter-from,
.slide-down-leave-to {
  opacity: 0;
  transform: translateY(-20px);
}

.status {
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
  padding: 16px 20px;
  border-radius: 12px;
  color: white;
  font-weight: 500;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.2);
}

.status.success {
  background: linear-gradient(135deg, #48bb78, #38a169);
}

.status.error {
  background: linear-gradient(135deg, #f56565, #e53e3e);
}

.status-content {
  display: flex;
  align-items: center;
  gap: 8px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .ip-query-tool {
    padding: 16px;
  }

  .header {
    flex-direction: column;
    gap: 16px;
  }

  .title-section {
    flex-direction: column;
    text-align: center;
  }

  .controls {
    width: 100%;
    justify-content: center;
  }

  .info-grid {
    grid-template-columns: 1fr;
  }

  .map-placeholder {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .history-item {
    flex-direction: column;
    gap: 8px;
    align-items: flex-start;
  }

  .stats-grid {
    grid-template-columns: 1fr;
  }
}
</style>